package com.tjoris.bpmstudio;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class BpmSpeedAction extends AbstractBpmOnAction
{
	private final URL fGetState;
	private final URL fGetPitchRange;
	private final URL fGetTempoRange;
	private final String fCommand;

	public BpmSpeedAction(final String playerName, final String playerNumber) throws MalformedURLException
	{
		super(playerName + "SetSpeed", playerName + " Set Speed");
		fGetState = new URL(kBASE_URL + "GETPITCHMODE" + playerNumber);
		fGetPitchRange = new URL(kBASE_URL + "GETPITCHRANGE" + playerNumber);
		fGetTempoRange = new URL(kBASE_URL + "GETTEMPORANGE" + playerNumber);
		fCommand = kBASE_URL + "SETSPEED" + playerNumber + "=";
	}
	
	public boolean isVariable()
	{
	    return true;
	}

	public void performAction(final int value)
    {
		try
		{
			final boolean isPitchMode = isPitchMode();
			final int range = getRange(isPitchMode) * 10;
			final double ration = (range * 2) / 127d;
			final int parameter = (int) ((value * ration) - range);
			new URL(fCommand + parameter).getContent();
		}
		catch (final Exception e)
		{
			e.printStackTrace();
		}
    }
	
	private boolean isPitchMode() throws IOException
	{
		return readData(fGetState) == 0;
	}
	
	private int getRange(final boolean isPitchMode) throws IOException
	{
		return readData(isPitchMode ? fGetPitchRange : fGetTempoRange);
	}
}
